<template>
    <view class="call-container">
        <!-- 拨号状态 -->
        <view v-if="callState === 'dialing'" class="state-container">
            <text class="calling-text">正在呼叫 {{ targetPhone }}...</text>
            <text class="virtual-number" v-if="virtualNumber">您的虚拟号码: {{ virtualNumber }}</text>
            <view class="dial-animation">
                <view class="circle" :style="{animationDelay: '0s'}"></view>
                <view class="circle" :style="{animationDelay: '0.2s'}"></view>
                <view class="circle" :style="{animationDelay: '0.4s'}"></view>
            </view>
            <button class="hangup-btn" @click="cancelCall">取消</button>
        </view>
        
        <!-- 来电状态 -->
        <view v-if="callState === 'incoming'" class="state-container">
            <text class="calling-text" v-if="virtualNumber">{{ virtualNumber }} 呼叫</text>
            <view class="call-actions">
                <button class="refuse-btn" @click="rejectCall">拒绝</button>
                <button class="accept-btn" @click="acceptCall">接听</button>
            </view>
        </view>
        
        <!-- 通话中状态 -->
        <view v-if="callState === 'talking'" class="state-container">
            <text class="calling-text">正在通话中</text>
            <text class="phone-info" v-if="callDirection === 'incoming'">来电号码: {{virtualNumber}}</text>
            <text class="phone-info" v-if="callDirection === 'outgoing'">您的号码: {{ virtualNumber }}</text>
            <text class="phone-info" v-if="callDirection === 'incoming'">您的号码: {{ targetPhone }}</text>
            <text class="phone-info" v-if="callDirection === 'outgoing'">对方号码: {{ targetPhone }}</text>
            <text class="call-duration">{{ formatDuration(callDuration) }}</text>
            <view class="call-controls">
                <button class="control-btn">静音</button>
                <button class="hangup-btn" @click="hangupCall">结束通话</button>
                <button class="control-btn">免提</button>
            </view>
        </view>
        
        <!-- 通话结束状态 -->
        <view v-if="callState === 'ended'" class="state-container">
            <text class="calling-text">{{ endReason }}</text>
            <text class="phone-info" v-if="callDirection === 'incoming'">来电号码: {{ virtualNumber }}</text>
            <text class="phone-info" v-if="callDirection === 'outgoing'">您的号码: {{ fromPhone }}</text>
            <text class="phone-info" v-if="callDirection === 'incoming'">您的号码: {{ targetPhone }}</text>
            <text class="phone-info" v-if="callDirection === 'outgoing'">对方号码: {{ virtualNumber }}</text>
            <button class="back-btn" @click="goBack">返回</button>
        </view>
    </view>
</template>

<script>
import websocket from '@/common/websocket.js'

let timer = null;
let heartbeatTimer = null;

export default {
    data() {
        return {
            myPhone: '',
            targetPhone: '',
            fromPhone: '',
            virtualNumber: '', // 虚拟号码字段
            callState: 'dialing', // dialing:拨号中 incoming:来电 talking:通话中 ended:已结束
            callDirection: 'outgoing', // outgoing:呼出 incoming:呼入
            callDuration: 0,
            endReason: '通话已结束',
            lastHeartbeat: 0 // 上次心跳时间
        };
    },
    onLoad(options) {
        this.myPhone = options.myPhone;
        this.targetPhone = options.targetPhone;
        this.virtualNumber = options.virtualNumber || '';
        this.callState = options.callState || 'dialing'; // 获取初始状态
        
        // 判断是呼出还是呼入
        if (options.isIncoming) {
            this.callState = 'incoming';
            this.callDirection = 'incoming';
            this.fromPhone = options.fromPhone;
        } else {
            // 发起呼叫
            this.initCall();
        }
    },
    onUnload() {
        // 页面关闭时清理定时器
        if (timer) {
            clearInterval(timer);
        }
        if (heartbeatTimer) {
            clearInterval(heartbeatTimer);
        }
    },
    mounted() {
        // 监听WebSocket消息
        websocket.on('message', (message) => {
            this.handleMessage(message);
        });
    },
    methods: {
        // 初始化呼叫
        initCall() {
            // 检查WebSocket连接状态，如果未连接则重新连接
            if (!websocket.isConnected) {
                websocket.init(this.myPhone);
            }
            
            // 等待连接成功后发送呼叫请求
            setTimeout(() => {
                if (websocket.isConnected) {
                    this.sendCallRequest();
                    // 启动心跳检测
                    this.startHeartbeat();
                } else {
                    // 如果连接还未建立，等待一段时间再尝试
                    const checkConnection = setInterval(() => {
                        if (websocket.isConnected) {
                            clearInterval(checkConnection);
                            this.sendCallRequest();
                            // 启动心跳检测
                            this.startHeartbeat();
                        }
                    }, 500);
                    
                    // 设置超时时间
                    setTimeout(() => {
                        clearInterval(checkConnection);
                        if (!websocket.isConnected) {
                            this.callState = 'ended';
                            this.endReason = '连接服务器失败';
                        }
                    }, 5000);
                }
            }, 1000);
        },
        
        // 启动心跳检测
        startHeartbeat() {
            this.lastHeartbeat = Date.now();
            heartbeatTimer = setInterval(() => {
                const now = Date.now();
                // 如果超过10秒没有收到心跳消息，认为连接已断开
                if (now - this.lastHeartbeat > 10000) {
                    this.callState = 'ended';
                    this.endReason = '连接已断开';
                    this.stopCallTimer();
                    clearInterval(heartbeatTimer);
                    // 强制更新视图
                    this.$forceUpdate();
                }
            }, 1000);
        },
        
        // 发送呼叫请求
        sendCallRequest() {
            const message = JSON.stringify({
                type: 'call',
                from: this.myPhone,
                to: this.targetPhone,
                virtualNumber: this.virtualNumber,
                time: new Date().getTime()
            });
            
            websocket.send(message);
        },
        
        // 处理收到的消息
        handleMessage(message) {
            try {
                const data = typeof message === 'string' ? JSON.parse(message) : message;
                
                console.log('收到WebSocket消息:', data);
                
                // 更新心跳时间
                this.lastHeartbeat = Date.now();
                
                switch (data.type) {
                    case 'call':
                        // 收到来电
                        this.callState = 'incoming';
                        this.callDirection = 'incoming';
                        this.fromPhone = data.from;
                        this.targetPhone = data.to;
                        // 只有在来电时才更新虚拟号码，避免挂断等消息覆盖
                        if (data.virtualNumber) {
                            this.virtualNumber = data.virtualNumber;
                        }
                        break;
                        
                    case 'answer':
                        // 对方已接听
                        this.callState = 'talking';
                        this.startCallTimer();
                        break;
                        
                    case 'hangup':
                        // 对方已挂断
                        this.callState = 'ended';
                        // 检查挂断原因
                        if (data.from === this.myPhone) {
                            this.endReason = '已挂断通话';
                        } else if (data.from === this.targetPhone || data.from === this.fromPhone) {
                            this.endReason = '对方已挂断';
                        } else {
                            this.endReason = '通话已结束';
                        }
                        this.stopCallTimer();
                        // 强制更新视图
                        this.$forceUpdate();
                        break;
                        
                    case 'reject':
                        // 呼叫被拒绝（如账户余额不足）
                        this.callState = 'ended';
                        this.endReason = data.reason || '呼叫被拒绝';
                        this.stopCallTimer();
                        // 强制更新视图
                        this.$forceUpdate();
                        break;
                }
            } catch (e) {
                console.error('解析消息错误：', e);
            }
        },
        
        // 接听电话
        acceptCall() {
            // 发送接听消息
            const message = JSON.stringify({
                type: 'answer',
                from: this.myPhone,
                to: this.fromPhone,
                virtualNumber: this.virtualNumber,
                time: new Date().getTime()
            });
            
            websocket.send(message);
            
            // 更新本地状态
            this.callState = 'talking';
            this.startCallTimer();
        },
        
        // 拒绝来电
        rejectCall() {
            // 发送挂断消息（拒接）
            const message = JSON.stringify({
                type: 'hangup',
                from: this.myPhone,
                to: this.fromPhone,
                virtualNumber: this.virtualNumber,
                time: new Date().getTime()
            });
            
            websocket.send(message);
            
            this.callState = 'ended';
            this.endReason = '已拒绝通话';
            this.stopCallTimer();
        },
        
        // 取消呼叫（拨号中取消）
        cancelCall() {
            // 发送挂断消息（取消呼叫）
            const message = JSON.stringify({
                type: 'hangup',
                from: this.myPhone,
                to: this.targetPhone,
                virtualNumber: this.virtualNumber,
                time: new Date().getTime()
            });
            
            websocket.send(message);
            
            this.callState = 'ended';
            this.endReason = '已取消呼叫';
            this.stopCallTimer();
        },
        
        // 挂断电话
        hangupCall() {
            // 发送挂断消息
            const message = JSON.stringify({
                type: 'hangup',
                from: this.myPhone,
                to: this.callDirection === 'incoming' ? this.fromPhone : this.targetPhone,
                virtualNumber: this.virtualNumber,
                time: new Date().getTime()
            });
            
            websocket.send(message);
            
            this.callState = 'ended';
            this.endReason = '已挂断通话';
            this.stopCallTimer();
        },
        
        // 开始通话计时器
        startCallTimer() {
            this.callDuration = 0;
            timer = setInterval(() => {
                this.callDuration++;
            }, 1000);
        },
        
        // 停止通话计时器
        stopCallTimer() {
            if (timer) {
                clearInterval(timer);
                timer = null;
            }
        },
        
        // 格式化通话时长
        formatDuration(seconds) {
            const min = Math.floor(seconds / 60);
            const sec = seconds % 60;
            return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
        },
        
        // 返回首页
        goBack() {
            uni.navigateBack({
                delta: 1
            });
        }
    }
};
</script>

<style scoped>
.call-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    background-color: #f5f5f5;
}

.state-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    padding: 50rpx;
}

.calling-text {
    font-size: 36rpx;
    margin-bottom: 20rpx;
    color: #333;
}

.phone-info {
    font-size: 30rpx;
    margin-bottom: 10rpx;
    color: #666;
}

.virtual-number {
    font-size: 30rpx;
    margin-bottom: 40rpx;
    color: #007aff;
    font-weight: bold;
}

.input-section {
    width: 80%;
    margin-bottom: 30rpx;
}

.input-label {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 15rpx;
    display: block;
}

.virtual-input {
    width: 100%;
    height: 80rpx;
    border: 2rpx solid #ddd;
    border-radius: 10rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    box-sizing: border-box;
}

.call-duration {
    font-size: 48rpx;
    margin: 30rpx 0;
    color: #007aff;
    font-weight: bold;
}

.dial-animation {
    position: relative;
    width: 200rpx;
    height: 200rpx;
    margin: 30rpx 0 60rpx 0;
}

.circle {
    position: absolute;
    width: 100%;
    height: 100%;
    border: 4rpx solid #007aff;
    border-radius: 50%;
    opacity: 0;
    animation: dial 2s infinite ease-in-out;
}

@keyframes dial {
    0% {
        transform: scale(0);
        opacity: 1;
    }
    100% {
        transform: scale(1.5);
        opacity: 0;
    }
}

.call-actions {
    display: flex;
    justify-content: space-around;
    width: 100%;
    margin-top: 60rpx;
}

.call-controls {
    display: flex;
    justify-content: space-around;
    width: 100%;
    margin-top: 60rpx;
}

.hangup-btn {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    background-color: #ff3b30;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    line-height: normal;
}

.accept-btn {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    background-color: #4cd964;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    line-height: normal;
}

.refuse-btn {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    background-color: #ff3b30;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    line-height: normal;
}

.control-btn {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
    background-color: #e5e5ea;
    color: #333;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
    line-height: normal;
}

.back-btn {
    margin-top: 60rpx;
    background-color: #007aff;
    color: white;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 30rpx;
}
</style>